import 'package:FineArt/core/api/module_api.dart';
import 'package:FineArt/page/search/component/TextTagWidget.dart';
import 'package:FineArt/utils/log_util.dart';
import 'package:FineArt/utils/size_config.dart';
import 'package:flutter/material.dart';

import '../../../constants.dart';

class ModuleGroupFilter extends StatefulWidget {
  final double width;
  final double height;
  final List<MoreFilterGroup> filterGroups;
  final Function confirmPress;
  final Function resetPress;
  final Widget bottom;

  const ModuleGroupFilter(
      {Key key,
      this.height = 25,
      this.width = 0,
      this.filterGroups,
      this.confirmPress,
      this.resetPress,
      this.bottom})
      : super(key: key);

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState

    return _ModuleGroupFilter();
  }
}

class _ModuleGroupFilter extends State<ModuleGroupFilter> {
  List<MoreFilterGroup> filterGroups;
  bool isFirst = true;

  @override
  Widget build(BuildContext context) {
    filterGroups = widget.filterGroups;
    if (isFirst) {
      isFirst = false;
      if (filterGroups.isNotEmpty) {
        MoreFilterGroup root = filterGroups.first;
        if (root.group_items.isNotEmpty) {
          MoreFilter mf = root.group_items[0];
          _selectItem(root, mf);
        }
      }
    }
    return Stack(
      children: [
        Positioned(
          child: InkWell(
            onTap: () {
              Navigator.of(context).pop();
            },
            child: Image.asset(
              "assets/images/icon_close.png",
              width: getPortraitSWidth(16.5),
              height: getPortraitSHeight(16.5),
            ),
          ),
          top: getPortraitSHeight(5),
          right: getPortraitSWidth(16),
        ),
        Positioned(
            child: moreFilterGroups(),
            top: getPortraitSHeight(26.5),
            bottom: getPortraitSHeight(50),
            width: SizeConfig.screenWidth),
        Positioned(
          child: getBottom(),
          bottom: 0,
          width: SizeConfig.screenWidth,
        )
      ],
    );
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

  Widget moreFilterGroups() {
    return Padding(
        padding: EdgeInsets.symmetric(
            vertical: getPortraitSHeight(5),
            horizontal: getPortraitSWidth(12.5)),
        child: ListView.builder(
            itemCount: filterGroups.length,
            itemBuilder: (BuildContext context, int index) {
              return filterGroupItem(index);
            }));
  }

  //超过20个显示下拉箭头
  final int rowCount = 20;

  Widget filterGroupItem(index) {
    if (filterGroups[index].isExpand == null)
      filterGroups[index].isExpand = true;
    bool isExpand = filterGroups[index].isExpand;
    List<TextTagWidget> list = _filterGroupItemSubItems(filterGroups[index]);
    bool isShowArrow = list.length > rowCount;
    return Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
      SizedBox(
        height: getPortraitSHeight(10),
      ),
      Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          InkWell(
            onTap: () {
              LogUtil.d("fold>>>>>");
            },
            child: Text(
              filterGroups[index].group_label,
              style: TextStyle(
                  fontSize: setSp(18),
                  color: text_black,
                  fontWeight: FontWeight.bold),
            ),
          ),
          if (isShowArrow)
            InkWell(
              child: Image.asset(
                isExpand
                    ? "assets/images/icon_arrow_up.png"
                    : "assets/images/icon_arrow_down.png",
                width: getPortraitSWidth(18),
                height: getPortraitSHeight(18),
              ),
              onTap: () {
                LogUtil.d("arrow down>>>>>");
                if (mounted) {
                  setState(() {
                    filterGroups[index].isExpand = !isExpand;
                  });
                }
              },
            )
        ],
      ),
      SizedBox(
        height: getPortraitSHeight(14),
      ),
      getExpandWidget(list, isExpand),
    ]);
  }

  Widget getExpandWidget(List<TextTagWidget> list, bool isExpand) {
    Widget widget = !isExpand
        ? ConstrainedBox(
            constraints: BoxConstraints(maxHeight: 50),
            child: Wrap(
                alignment: WrapAlignment.start,
                spacing: getPortraitSWidth(8),
                runSpacing: getPortraitSHeight(16),
                children: list),
          )
        : Wrap(
            children: list,
            alignment: WrapAlignment.start,
            spacing: getPortraitSWidth(8),
            runSpacing: getPortraitSHeight(16),
          );
    return widget;
  }

  void _selectItem(MoreFilterGroup group, MoreFilter item) {
    if (item.selected) {
      setState(() {
        int gLevel = group.level;
        LogUtil.d(
            "item.selected remove group.level ${group.level}  ");
        for (MoreFilter _item in group.group_items) {
          _item.selected = false;
        }
        if (!group.asFilterObject) {
          //如果时分类，选中时，动态改变下级内容，如果是标签，则不需要
          int levels = filterGroups.length;
          int current_level = group.level;
          LogUtil.d(
              "item.selected remove current_level $current_level  levels $levels");
          if (levels > current_level) {
            for (int i = 0; i < levels - current_level; i++) {
              filterGroups.removeLast();
            }
          }
        }
      });
      return;
    }
    LogUtil.d("item.selected ${item.selected}");
    setState(() {
      for (MoreFilter _item in group.group_items) {
        _item.selected = false;
      }
      item.selected = true;
      if (!group.asFilterObject) {
        //如果时分类，选中时，动态改变下级内容，如果是标签，则不需要
        int levels = filterGroups.length;
        int current_level = group.level;
        LogUtil.d(
            "item.selected 000000000000 current_level $current_level  levels $levels");
        if (levels > current_level) {
          for (int i = 0; i < levels - current_level; i++) {
            filterGroups.removeLast();
          }
        }
      }
    });

    if (item.children != null) {
      LogUtil.d("item.selected 1111111111111111111111 add children ");
      for (MoreFilter mf in item.children.group_items) {
        mf.selected = false;
      }
      filterGroups.add(item.children);
      item.children.level = filterGroups.length;
    } else if (item.filters != null) {
      LogUtil.d("item.selected 22222222222222222222");
      for (Filter filter in item.filters) {
        //把filter当成MoreFilterGroup来展示
        List<MoreFilter> _moreFilters = [];
        for (String value in filter.values) {
          MoreFilter mf = MoreFilter(label: value);
          mf.selected = false;
          _moreFilters.add(mf);
        }
        MoreFilterGroup _group = MoreFilterGroup(
            group_label: filter.markname, group_items: _moreFilters);
        _group.asFilterObject = true;
        filterGroups.add(_group);
        _group.level = filterGroups.length;
      }
    }
  }

  List<TextTagWidget> _filterGroupItemSubItems(MoreFilterGroup group) {
    List<TextTagWidget> tList = [];
    if (group.group_items.isEmpty) return tList;

    for (var i = 0; i < group.group_items.length; i++) {
      MoreFilter item = group.group_items[i];
      tList.add(TextTagWidget(
          text: item.label,
          color: item.selected ? Colors.white : text_black,
          bgColor: item.selected ? Colors.red : bg_input,
          index: i,
          selected: item.selected,
          textClick: (text, index) {
            _selectItem(group, item);
          }));
    }
    return tList;
  }

  Widget getBottom() {
    return Row(
      children: [
        Expanded(
            child: FlatButton(
          onPressed: () {
            resetAction();
          },
          child: Text(
            "重置",
            style: TextStyle(fontSize: setSp(18), color: text_black),
          ),
          height: 49,
          color: bg_button_gray,
        )),
        Expanded(
            child: FlatButton(
          onPressed: () {
            widget.confirmPress();
          },
          child: Text(
            "确定",
            style: TextStyle(fontSize: setSp(18), color: Colors.white),
          ),
          height: 49,
          color: red_main,
        )),
      ],
    );
  }

  resetAction() {
    setState(() {
      if (filterGroups.length > 0) {
        int c = filterGroups.length - 1;
        for (int i = 0; i < c; i++) {
          filterGroups.removeLast();
        }

        MoreFilterGroup g = filterGroups.first;
        for (int i = 0; i < g.group_items.length; i++) {
          g.group_items[i].selected = false;
        }
      }
    });
  }
}
